#!/bin/bash
mainPath="${HOME}/temp/yapai/"
#projectName="shuiliandong"
#branchName="dev"
environ=$1
project=$2
install=""
upload=""
profile="ypcli"
helpflag=""
property=""
keep_branch="false"
copy2deploy="false"
#tes
while getopts ":e:c:p:i:u:P:h:k:D:" opt
do
    case $opt in
        e)
        environ=$OPTARG
        echo "您输入的环境配置:$environ"
        ;;
        c)
        copy2deploy=$OPTARG
        echo "您输入的是否发布本地配置:$copy2deploy"
        ;;
        p)
        project=$OPTARG
        echo "您输入的项目配置:$project"
        ;;
        i)
        install=$OPTARG
        echo "您输入的打包开关配置:$install"
        ;;
        u)
        upload=$OPTARG
        echo "您输入的上传开关配置:$upload"
        ;;
        P)
        profile=$OPTARG
        echo "您输入的打包环境配置:$profile"
        ;;
        D)
        property=$OPTARG
        echo "Your system property is : ${property}"
        ;;
        h)
        helpflag=$OPTARG
        echo "您输入的帮助手册:$helpflag"
        ;;
        k)
        keep_branch=$OPTARG
        echo "是否已项目分支为准(default: false):$keep_branch"
        ;;
        ?)
        echo "未知参数,你可以这样使用 : sh shuiliandong.sh -e 111 -p sld -i install -u upload -P profile -Dyplicdis"
        exit 1;;
    esac
done
getRealJarFile(){
  recursion=$2
  MAIN_FILE="META-INF/MANIFEST.MF"
  BASE_TEMP_FD=${HOME}/temp/zip
  if [[ ! -d ${BASE_TEMP_FD} ]]
  then
    mkdir -p ${BASE_TEMP_FD}
  fi
  JAR_FILES=$1
  for JARFILE in ${JAR_FILES[@]}
  do
    if [[ -f ${JARFILE} ]]
    then
      FN=`md5sum ${JARFILE} | awk '{print $1}'`
      unzip ${JARFILE} ${MAIN_FILE} -d ${BASE_TEMP_FD}/${FN}
      cat ${BASE_TEMP_FD}/${FN}/${MAIN_FILE} | grep "Main-Class"
    fi
    if [[ $? -eq 1 || ! -f ${JARFILE} ]]
    then
      if [[ $recursion == "true" ]]
      then
        JAR_FILES=`find $mainPath$projectName  -type f -name '*.jar' | xargs ls -t `
        getRealJarFile "$JAR_FILES" false
      else
        echo "continue"
        continue
      fi
    else
      echo $JARFILE
      break
    fi
  done
}

dotest(){
  echo "enter ..."
  JAR_FILES=(`cd $mainPath$projectName/${SUB_PATH} 2>/dev/null;ls -t ${scpProjectName}*.${projectType} 2>/dev/null | sed "s:^:$mainPath$projectName/${SUB_PATH}:"`)
  if [[ $? -ge 1 || -z ${JAR_FILES} ]]
  then
    JAR_FILES=(hello.jar)
  fi
  getRealJarFile ${JAR_FILES} true
}
# currentHome=`pwd`hello
# currentHome=$(cd "$(dirname "$0")";pwd)
name=`uname -s`
if [[ "${name}" = "Linux" ]]; then
currentHome=$( dirname "$(readlink -f  ${BASH_SOURCE[0]})" )
else
currentHome=$( dirname "$(greadlink -f  ${BASH_SOURCE[0]})" )
fi
projectName=(`cat ${currentHome}/project/${project} | jq -r '.project_name'`)
branchName=(`cat ${currentHome}/project/${project} | jq -r '.branch_name'`)
if [[ "$keep_branch" == "true" ]]
then
  branchName=""
fi
if [[ -z ${branchName} ]]
then
  branchName=`cd $mainPath$projectName ; git branch | grep -E '^\*' | sed -n '1p' | awk '{print $2}'`
  echo "@@@@@@@@@@@@@@22"
  echo $branchName
fi
gitPath=(`cat ${currentHome}/project/${project} | jq -r '.git_path'`)
PORT=(`cat ${currentHome}/project/${project} | jq -r '.port'`)
scpProjectName=(`cat ${currentHome}/project/${project} | jq -r '.scp_project_name'`)
projectType=(`cat ${currentHome}/project/${project} | jq -r '.project_type'`)
MAIN_BRANCH=(`cat ${currentHome}/project/${project} | jq -r '.main_branch'`)
if [[ -z $MAIN_BRANCH ]]
then
  MAIN_BRANCH=$branchName
fi
if [ -d "$mainPath$projectName" ]
then
    echo "[$mainPath$projectName] exists"
    cd $mainPath$projectName
    git checkout ${MAIN_BRANCH}
    git pull origin ${MAIN_BRANCH}
    git checkout $branchName
    git merge ${MAIN_BRANCH}
    git pull origin $branchName
else
    echo "[$mainPath$projectName] not exists"
    echo $gitPath
    echo $branchName
    echo $mainPath
    echo $projectName
    git clone ${gitPath} -b $branchName "${mainPath}$projectName"
    cd $mainPath$projectName
    git checkout ${MAIN_BRANCH}
    git pull origin ${MAIN_BRANCH}
    git checkout $branchName
    git merge ${MAIN_BRANCH}
fi
# 开始打包
#mavenstatus="$(mvn clean install -Pzxhtom -DskipTests=true)"
#mavenstatus=`mvn clean install -Pzxhtom -DskipTests`
echo 开关配置${install}
if [[ ! -f ${currentHome}/mvninstall/${projectName}/mvninstall.log ]]
then
  echo "create log file"
  mkdir -p ${currentHome}/mvninstall/${projectName}/
  touch ${currentHome}/mvninstall/${projectName}/mvninstall.log
fi
if [[ -n $install ]]
then
    piLine=`cat ${currentHome}/mvninstall/${projectName}/mvninstall.log | wc -l`
    sleep 2
    piLine2=`cat ${currentHome}/mvninstall/${projectName}/mvninstall.log | wc -l`
    if [[ $piLine < $piLine2 ]]
    then
        echo "已经有别的进程在打包"${projectName}"；请结束后再开始操作，或者请使用免打包方式"
        exit
    fi
    echo 开始打包
    echo > ${currentHome}/mvninstall/${projectName}/mvninstall.log
    mvn clean install -DskipTests -P zxhtom,${profile} -D${property} > ${currentHome}/mvninstall/${projectName}/mvninstall.log 2>&1 &
else
  SUB_PATH=(`cat ${currentHome}/project/${project} | jq -r '.sub_path'`)
  if [[ -d ${mainPath}/${projectName}/${SUB_PATH} ]]
  then
    file=`ls -1 ${mainPath}/${projectName}/${SUB_PATH} | grep -E '.*\.jar_back'`
    if [[ ! -z $file ]]
    then
      cp ${mainPath}/${projectName}/${SUB_PATH}/${file} ${mainPath}/${projectName}/${SUB_PATH}/`echo ${file} | awk -F '_back' '{print $1}'`
    fi
  fi
  echo ----------
fi
if [[ ! -f ${currentHome}/time/${projectName} ]]
then
  mkdir -p ${currentHome}/time
 touch ${currentHome}/time/${projectName}
fi
preTime=`cat ${currentHome}/time/${projectName} | sed -n '$p'`
if [[ $preTime =~ [0-9]+ ]]
then
    echo 预计用时:$preTime
else
    preTime=1000
fi
SLEEPTIME=$((preTime/100+1))
mavenstatus=""
failmavenstatus=""
i=0
str='#'
ch=('|' '\' '-' '/')
index=0
totali=0
while [ $i -le 100 ]
do
    if [[ $i -le 99 ]]
    then
        printf "[%-100s][%d%%][%c]\r" $str $(($i)) ${ch[$index]}
        str+='#'
        let i++
        let index=i%4
    fi
    #echo $i
    mavenstatus=`sed -n '/\[INFO\] BUILD SUCCESS/p' ${currentHome}/mvninstall/${projectName}/mvninstall.log`
    logLine=`cat ${currentHome}/mvninstall/${projectName}/mvninstall.log | wc -l`
    sleep $SLEEPTIME
    #echo $mavenstatus
    #echo $i
    #echo ${#mavenstatus}
    if [[ ${#mavenstatus} > 0 ]]
    then
        i=100;
        str=####################################################################################################
        printf "[%-100s][%d%%][%c]\r" $str $(($i)) ${ch[$index]}
        break;
    fi
    failmavenstatus=`sed -n '/\[INFO\] BUILD FAILURE/p' ${currentHome}/mvninstall/${projectName}/mvninstall.log`
    #echo ${failmavenstatus}
    if [[ -n ${failmavenstatus} ]]
    then
        echo 打包失败
        exit
    fi
    if [[ $i -ge 90 ]]
    then
        sthigh=$(($SLEEPTIME+$i-89))
        sleep $sthigh
        nlogLine=`cat ${currentHome}/mvninstall/${projectName}/mvninstall.log | wc -l`
        if [[ $nlogLine -eq $logLine ]]
        then
            let totali++
        fi
        if [[ $totali -ge 10 ]]
        then
            echo 打包失败,是时候该放手了.....
            exit
        fi
    fi
done
printf "\n"
echo "安装完成"${mavenstatus}
# 获取整个打包用时
# totaltime=`sed -n '/\[INFO\] Total time:  [0-9]*:[0-9]* [a-zA-Z]*/p' ${currentHome}/mvninstall/${projectName}/mvninstall.log`
# if [[ ${totaltime} =~  .*([0-9]*):([0-9]*) ([a-zA-Z]*) ]]
# then
# fi
if [[ -n $mavenstatus ]] && [[ -n ${upload} ]]
then
     cd ${currentHome}
     TOTALINSTALL=`sh ${currentHome}/regex.sh ${projectName}| sed -n '$p'`
     echo 一共耗时：${TOTALINSTALL}
     if [[ -n $install ]]
     then
        echo ${TOTALINSTALL} > ${currentHome}/time/${projectName}
     fi
     # 读取服务器
     IP=(`cat ${currentHome}/enviroment/${environ} | jq -r '.ip'`)
     EPORT=(`cat ${currentHome}/enviroment/${environ} | jq -r '.port'`)
     if [[ "${EPORT}" -gt 0 ]] 2>/dev/null
     then
       echo "you set port=${EPORT}"
     else
       EPORT=22
     fi
     # 读取用户名
     USER_NAME=(`cat ${currentHome}/enviroment/${environ} | jq -r '.user_name'`)
     # 读取密码
     PASSWORD=(`cat ${currentHome}/enviroment/${environ} | jq -r '.password'`)
     # 读取存放位置
     SAVE_PATH=(`cat ${currentHome}/enviroment/${environ} | jq -r '.save_path'`)

    SUB_PATH=(`cat ${currentHome}/project/${project} | jq -r '.sub_path'`)
    
    JAR_FILES=(`cd $mainPath$projectName/${SUB_PATH} 2>/dev/null;ls -t ${scpProjectName}*.${projectType} 2>/dev/null`)
    if [[ $? -ge 1 ]]
    then
      JAR_FILES=(hello.jar)
    fi
    JARFILE=${JAR_FILES[0]}
    if [[ ${project} != 'tb' ]] 
    then
      JARFILE=`dotest ${JAR_FILES}`
      echo "$JARFILE"
      JARFILE=`echo "$JARFILE" | sed -n '$p'`
      # dynic serach jar and fd
      SUB_PATH=${JARFILE##$mainPath$projectName/}
      SUB_PATH=${SUB_PATH%/*}/
      JARFILE=${JARFILE##*/}
    fi
     if [[ "${SAVE_PATH:0:1}" != "/" ]]
     then
       SAVE_PATH="~/${SAVE_PATH}"
     fi
     check_ypstart_exists=`sshpass -p $PASSWORD ssh -o StrictHostKeyChecking=no -p ${EPORT} $USER_NAME@$IP "ypstart -help 2>&1 | wc -l"`
     echo --------------------------------------------------------
     echo $check_ypstart_exists
     if [[ ${project} != 'tb' ]] && [[ "${check_ypstart_exists}" -gt 1 ]]
     then
        get_password_cmd="ps -ef | grep services | grep -v grep | grep -E '.*/bootstrap.yml' | head -1 " | awk '{print $10}'
        encrypted_password=`sshpass -p $PASSWORD ssh -o StrictHostKeyChecking=no -p ${EPORT} $USER_NAME@$IP "ps -ef | grep services | grep -v grep | grep -E '.*/bootstrap.yml' | grep -E 'javaagent' | head -1 " | awk '{print $10}'`
        echo ---------------------------------------------------------------------------------
        echo ${encrypted_password}
        if [[ -z ${encrypted_password} ]]
        then
          sh ${currentHome}/classfinal.sh $mainPath$projectName/${SUB_PATH}$JARFILE
        else
          sh ${currentHome}/classfinal.sh $mainPath$projectName/${SUB_PATH}$JARFILE ${encrypted_password} true
        fi
     fi
     simple_branch_name=${branchName##*[-|_]}
     if [[ ${copy2deploy} == "true" ]]
     then
       if [[ ! -d ${HOME}/temp/deploy/${simple_branch_name} ]]
       then
         mkdir -p ${HOME}/temp/deploy/${simple_branch_name}
       fi
       cp -rvf $mainPath$projectName/${SUB_PATH}$JARFILE ${HOME}/temp/deploy/${simple_branch_name}/
       exit 0
     fi
     echo "$projectName 构建成功.........即将上传文件"
     result=`sshpass -p $PASSWORD ssh -o StrictHostKeyChecking=no -p ${EPORT} $USER_NAME@$IP "ls -al $SAVE_PATH | grep $projectName"`
     if [[ -z $result ]]
     then
         echo not
         sshpass -p $PASSWORD ssh -o StrictHostKeyChecking=no -p ${EPORT} $USER_NAME@$IP "mkdir -p ${SAVE_PATH}/$projectName"
     fi
     sshpass -p $PASSWORD ssh -o StrictHostKeyChecking=no -p ${EPORT} $USER_NAME@$IP "cd  $SAVE_PATH/$projectName;ls -1 | grep -E 'jar$' | sort -r | sed -n -e '6,/$/p' | xargs rm -rf"
     sshpass -p $PASSWORD  scp -P ${EPORT} -o ConnectTimeout=20 $mainPath$projectName/${SUB_PATH}$JARFILE $USER_NAME@$IP:$SAVE_PATH/$projectName &
     SOURCE_MD5SUM=`md5sum $mainPath$projectName/${SUB_PATH}$JARFILE | awk '{print $1}'`
     TARGET_MD5SUM=""
     str='#'
     ch=('|' '\' '-' '/')
     index=0
     port=$1
     i=0
     while [[ $i -le 25 ]]
     do
      TARGET_MD5SUM=`sshpass -p $PASSWORD ssh -o StrictHostKeyChecking=no -p ${EPORT} $USER_NAME@$IP "md5sum ${SAVE_PATH}/${projectName}/${JARFILE}" | awk '{print $1}'`
      printf "[%-25s][%d%%][%c]\r" $str $(($i*4)) ${ch[$index]}
      str+='#'
      let i++
      let index=i%4
      if [[ "${SOURCE_MD5SUM}" == "${TARGET_MD5SUM}" ]]
      then
          if [[ $i <25 ]]
          then
              i=25;
              str=#########################
          fi
      fi
     done
     printf "\n"
     echo "上传结束,即将启动重启脚本"
     sshpass -p $PASSWORD ssh -o StrictHostKeyChecking=no -p ${EPORT} $USER_NAME@$IP "ls -1 ${SAVE_PATH}/${projectName} | grep -E '^restart.sh$'" >/dev/null
     if [[ $? -eq 1 ]]
     then
     sshpass -p $PASSWORD  scp -P ${EPORT} -o ConnectTimeout=20 ${currentHome}/start/restart.sh $USER_NAME@$IP:$SAVE_PATH/$projectName
     fi
     if [[ ${project} == 'tb' ]]
     then
     echo tb项目特殊处理
     sshpass -p $PASSWORD ssh -o StrictHostKeyChecking=no -p ${EPORT} $USER_NAME@$IP "cd  $SAVE_PATH/$projectName; sudo rpm -Uvh --force thingsboard.rpm "
     sshpass -p $PASSWORD ssh -o StrictHostKeyChecking=no -p ${EPORT} $USER_NAME@$IP "sudo systemctl restart thingsboard"
     sshpass -p $PASSWORD ssh -o StrictHostKeyChecking=no -p ${EPORT} $USER_NAME@$IP "sudo systemctl daemon-reload"
     sshpass -p $PASSWORD ssh -o StrictHostKeyChecking=no -p ${EPORT} $USER_NAME@$IP "tail -f /var/log/thingsboard/thingsboard.log > /dev/null 2>&1 & "
     exit
     elif [[ ${check_ypstart_exists} -gt 1 ]]
     then
     startstatus=`sshpass -p $PASSWORD ssh -o StrictHostKeyChecking=no -p ${EPORT} $USER_NAME@$IP "cd  $SAVE_PATH/$projectName; ypstart -r 1 ${projectName} > /dev/null 2>&1 & "`
     else
     startstatus=`sshpass -p $PASSWORD ssh -o StrictHostKeyChecking=no -p ${EPORT} $USER_NAME@$IP "cd  $SAVE_PATH/$projectName; sh restart.sh > /dev/null 2>&1 & "`
     fi
     i=0
    str='#'
    ch=('|' '\' '-' '/')
    index=0
    port=$1
    while [ $i -le 25 ]
    do
        printf "[%-25s][%d%%][%c]\r" $str $(($i*4)) ${ch[$index]}
        str+='#'
        let i++
        let index=i%4
        pid=`sshpass -p $PASSWORD ssh $USER_NAME@$IP "netstat -ntl | grep :${PORT}" | awk -F "[ :]+" '{print $4}'`
        #pid=`sshpass -p $PASSWORD ssh $USER_NAME@$IP "lsof -i:$PORT" | awk -F "[ ]+" 'NR>1{print $2}'`
        #pid=`sshpass -p $PASSWORD ssh $USER_NAME@$IP "ps -ef | grep $projectName | grep -v grep" | awk '{print $2}'`
        if [[ -n $pid ]]
        then
            if [[ $i <25 ]]
            then
                i=25;
                str=#########################
            fi
        fi
        sleep 2
    done
    printf "\n"
    if [[ -z $pid ]]
    then
        stime=`sshpass -p $PASSWORD ssh $USER_NAME@$IP "ps -ef | grep $projectName | grep -v grep" | awk '{print $5}'`
        echo "检测到待启动服务初次运行时间："+$stime
    fi
    echo "启动结束！${pid}"
elif [[ -z ${upload} ]]
then
    echo "您未设置上传指令，此次发包结束，最近一次操作为【install success】,可以 -u upload 进行上传"
else
     echo "${projectName}构建失败........"
     #echo $mavenstatus
fi
